package com.ybkj.chat.module.mine.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.ybkj.chat.R;
import com.ybkj.chat.base.BaseMvpActivity;
import com.ybkj.chat.bean.ProvinceBean;
import com.ybkj.chat.manager.FullyGridLayoutManager;
import com.ybkj.chat.ui.adapter.GridImageAdapter;
import com.ybkj.chat.ui.dialog.PpwClearCache;
import com.ybkj.chat.ui.dialog.PpwEmotion;
import com.ybkj.chat.ui.view.recyclerview.XRecyclerView;
import com.ybkj.chat.utils.GetJsonDataUtil;
import com.ybkj.chat.utils.LogUtil;
import com.ybkj.chat.utils.ToastUtil;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * @author yyj
 * @create 2019-02-28 11:32
 * @Describe
 */
public class EditInformationActivity extends BaseMvpActivity {
    @BindView(R.id.rv_edit_information)
    XRecyclerView rvEditInformation;
    @BindView(R.id.lnl_root)
    LinearLayout lnlRoot;

    private static final int EDIT_ADD_AVATAR = 112;
    private static final int MSG_LOAD_DATA = 113;

    private GridImageAdapter gridImageAdapter;
    private PpwEmotion ppwEmotion;
    private Thread thread;
    private List<LocalMedia> selectList = new ArrayList<>();
    private List<ProvinceBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private Handler mHandler;
    private int selectSum = 8;
    private FullyGridLayoutManager manager;

    @Override
    protected void injectPresenter() {

    }

    @Override
    protected void initTitle() {
        setTitleText("捣蛋鬼");
        setRightText("保存");
        setRightTextColor(R.color.color_dfd);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_information;
    }

    @Override
    protected void initView() {
        gridImageAdapter = new GridImageAdapter(this, onAddPicClick0);
        manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        rvEditInformation.setLayoutManager(manager);
        rvEditInformation.setAdapter(gridImageAdapter);
    }

    @Override
    protected void initData() {
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_LOAD_DATA:
                        if (thread == null) {//如果已创建就不再重新创建子线程了
                            thread = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    // 子线程中解析省市区数据
                                    initJsonData();
                                }
                            });
                            thread.start();
                        }
                        break;
                }
            }
        };
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClick0 = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(EditInformationActivity.this)
                    .openGallery(PictureMimeType.ofImage())
                    .maxSelectNum(selectSum)
                    .minSelectNum(1)
                    .imageSpanCount(4)
                    .selectionMode(PictureConfig.MULTIPLE)
                    .selectionMedia(selectList)// 是否传入已选图片
                    .forResult(EDIT_ADD_AVATAR);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case EDIT_ADD_AVATAR:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
//                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    gridImageAdapter.setList(selectList);
                    gridImageAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @OnClick({R.id.lnl_address, R.id.lnl_birthday, R.id.lnl_emotion, R.id.lnl_hometown, R.id.tv_change_bg})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_change_bg:
                break;
            case R.id.lnl_address:
                showPickerView();
                break;
            case R.id.lnl_birthday:
                TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {

                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .build();
                pvTime.show();
                break;
            case R.id.lnl_hometown:
                showPickerView();
                break;
            case R.id.lnl_emotion:
                ppwEmotion = new PpwEmotion(this);
                ppwEmotion.setAnimationStyle(R.style.choose_item_dialog_animation);
                ppwEmotion.showAtLocation(lnlRoot, Gravity.BOTTOM, 0, 0);
                ppwEmotion.setBackgroundAlpha(this, 0.5f);
                ppwEmotion.setOnItemClickListener(new PpwClearCache.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v) {
                        switch (v.getId()) {
                            case R.id.tv_clear:
                                break;
                            case R.id.tv_cancel:
                                break;
                        }
                    }
                });
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String tx = opt1tx + opt2tx;
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(options1Items, options2Items);//二级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<ProvinceBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                /*if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }*/
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);
        }

    }

    public ArrayList<ProvinceBean> parseData(String result) {//Gson 解析
        ArrayList<ProvinceBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                ProvinceBean entity = gson.fromJson(data.optJSONObject(i).toString(), ProvinceBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
}
